#Fig.1a
library(rnaturalearth)
library(dplyr)
library(terra)
library(sf)
library(ggplot2)
library(readxl)
library(ggspatial)

data_path <- "/Users/lvchunhua/Downloads/Exudation"

china <- ne_countries(scale = "medium", returnclass = "sf") |>
  filter(admin == "China") |>
  st_transform("EPSG:4326")

nine_line <- st_read(file.path(data_path, "entity_tt")) |>
  st_transform("EPSG:4326")

eco_map <- rast(file.path(data_path, "2020/eco2020_1km"))
eco_map_wgs84 <- project(eco_map, "EPSG:4326")
china_vect <- vect(china)
eco_map_mask <- crop(eco_map_wgs84, china_vect)

eco_map_mask <- round(eco_map_mask)
eco_map_mask <- clamp(eco_map_mask, lower = 1, upper = 7, values = TRUE)
eco_map_mask <- as.factor(eco_map_mask)

point_df <- read_excel(file.path(data_path, "Source Data_Fig. 1.xlsx"), sheet = "Fig. 1a")
points <- st_as_sf(point_df, coords = c("Longitude", "Latitude"), crs = 4326)

eco_colors <- c("2" = "#228B22")
eco_labels <- c("2" = "Forest ecosystems")

p1 <- ggplot() +
  layer_spatial(eco_map_mask) +
  scale_fill_manual(values = eco_colors, labels = eco_labels, name = " ", na.value = "transparent", na.translate = FALSE) +
  geom_sf(data = nine_line, color = "black", linewidth = 0.4) +
  geom_sf(data = points, color = "black", fill = "white", size = 4, shape = 21, stroke = 0.7) +
  coord_sf(xlim = c(73, 136), ylim = c(3, 54)) +
  annotation_scale(location = "br", width_hint = 0.2, pad_x = unit(1, "cm"), pad_y = unit(0.5, "cm"), line_width = 0.6, text_cex = 1) +
  annotation_north_arrow(location = "tl", which_north = "true", style = north_arrow_fancy_orienteering) +
  theme_minimal() +
  theme(
    plot.caption = element_text(hjust = 0, size = 6),
    text = element_text(size = 12),
    legend.position = c(0.5, 0.93),
    legend.key.size = unit(0.5, "cm"),
    legend.key = element_rect(color = NA),
    panel.grid.major = element_line(color = "grey85", size = 0.2)
  )

p1
ggsave("Fig.1a.jpg", p1, units="cm", width=21, height=13, dpi=1000)


#Fig.1b
library(readxl)
library(dplyr)
library(ggplot2)
library(ggpubr)
library(lmerTest)
rawdata <- as.data.frame(read_excel("Source Data_Fig. 1.xlsx", sheet = "Fig. 1b"))
str(rawdata)

exudation_summary <- rawdata %>%
  group_by(Mycorrhizal_types) %>%
  summarise(Mean_Exudation = mean(Exudation, na.rm = TRUE))
print(exudation_summary)

rawdata <- as.data.frame(read_excel("Source Data_Fig. 1.xlsx", sheet = "Fig. 1b"))
rawdata$Mycorrhizal_types <- factor(rawdata$Mycorrhizal_types, levels = c("AM", "ECM"))
fit_lmm_exu <- lmer(Exudation ~ Mycorrhizal_types + (1 | Site:Species), data = rawdata)
summary(fit_lmm_exu)

p_val_exu <- summary(fit_lmm_exu)$coefficients[ "Mycorrhizal_typesECM", "Pr(>|t|)"]
p_val_exu

p2 <- ggplot(rawdata, aes(x = Mycorrhizal_types, y = Exudation)) +
  theme(panel.background = element_blank()) +
  geom_boxplot(aes(fill = Mycorrhizal_types), alpha = 0.3, colour = "#474747", outlier.shape = NA, size = 0.6 ) +
  geom_jitter(aes(fill = Mycorrhizal_types), width = 0.15, size = 3, shape = 21, color = "black", stroke = 0.4, alpha = 0.7) +
  scale_fill_manual(values = c("AM" = "#F39F4E", "ECM" = "#98CFE6")) +
  scale_x_discrete(limits = c("AM", "ECM")) +
  scale_y_continuous(limits = c(50, 440), breaks = c(100, 200, 300, 400)) +
  annotate("text", x = 1, y = 55, label = "n = 120", size = 5) +
  annotate("text", x = 2, y = 55, label = "n = 81", size = 5) +
  annotate("segment", x = 1, xend = 2, y = 400, yend = 400) +
  annotate("segment", x = 1, xend = 1, y = 400, yend = 385) +
  annotate("segment", x = 2, xend = 2, y = 400, yend = 385) +
  annotate("text", x = 1.5, y = 420, label = "italic(P) < 0.001", size = 4.5, parse = TRUE)+
  labs(x = "Mycorrhizal types", y = expression(paste("Root exudation rate (", mu, "g C ", g^{-1}, " ", h^{-1}, ")"))) +
  theme_bw() +
  theme(
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    axis.title = element_text(size = 15, colour = "black"),
    axis.text = element_text(size = 13, colour = "black"),
    legend.position = "none",
    panel.border = element_rect(size = 0.9, color = "black"),
    aspect.ratio = 1.1
  )

print(p2)
ggsave("Fig.1b.jpg", p2, units = "cm", width = 10, height = 12, dpi = 1000)


#Fig.1c
library(readxl)
library(dplyr)
library(V.PhyloMaker)
library(ape)
library(ggtree)
library(ggtreeExtra)
library(tidyr)
library(scales)

rrdata <- as.data.frame(read_excel("Source Data_Fig. 1.xlsx", sheet = "Fig. 1c"))

traits_means <- rrdata %>%
  group_by(Species) %>%
  summarise(Mycorrhizal_types = first(Mycorrhizal_types), Phytodiversity = first(Phytodiversity), Exudation_mean = mean(Exudation, na.rm = TRUE),
            .groups = "drop") %>%
  mutate(Exudation = (Exudation_mean - min(Exudation_mean)) / (max(Exudation_mean) - min(Exudation_mean)))

sp_lis <- traits_means %>%
  transmute(species = Species, genus = sub("_.*", "", Species), family = NA)

sp_tree <- phylo.maker(sp.lis = sp_lis)
sp_tr <- sp_tree$scenario.3
write.tree(sp_tr, file = "sp_tree.tre")

tree <- read.tree("sp_tree.tre")
tree$tip.label <- gsub(" ", "_", tree$tip.label)

data_for_tree <- traits_means %>%
  mutate(species = Species) %>%
  filter(species %in% tree$tip.label)

group_mapping <- split(data_for_tree$species, data_for_tree$Phytodiversity)
tree <- groupOTU(tree, group_mapping)

colors <- c("Angiosperms" = "#d17532", "Gymnosperms" = "#66cc66")
p <- ggtree(tree, aes(color = group), layout = "fan") + 
  scale_color_manual(values = colors, name = "Groups") +
  geom_tiplab(aes(label = label), size = 2, align = TRUE, offset = 0.1) +
  theme_tree2() +
  theme(axis.text = element_blank(), axis.ticks = element_blank())
p <- p +
  geom_fruit(data = data_for_tree, geom = geom_point, mapping = aes( y = species, size = Exudation), color = "#81B21F", offset = 0.8, pwidth = 0.01) +
  scale_size_continuous(range = c(1, 5), name = "Root exudation rate")
myco_data <- data_for_tree %>%
  arrange(match(species, tree$tip.label)) %>%
  select(species, type = Mycorrhizal_types) %>%
  drop_na()
p3 <- p +
  geom_fruit(data = myco_data, geom = geom_bar, mapping = aes( y = species, fill = type, x = 0.7), orientation = "y", width = 1, offset = 0.1, stat = "identity") +
  scale_fill_manual(values = c( "AM"  = "#F39F4E", "ECM" = "#98CFE6"), name = "Mycorrhizal types") +
  theme(legend.position = "right")
print(p3)
ggsave("Fig.1c.jpg", p3, device = "jpeg", units = "cm", width=23, height=23, dpi=1000)


#Fig.1d
library(readxl)
library(plspm)

en <- read_excel("Source Data_Fig. 1.xlsx", sheet = "Fig. 1d")
en <- na.omit(en)

en$Mycorrhizal_types_num <- ifelse(en$Mycorrhizal_types == "ECM", 1, 0)
en$CS <- en$Clay + en$Silt

semdata <- en[, c("MAT", "MAP", "Exudation", "Mycorrhizal_types_num", "AvaiP", "TP", "RD", "SRL", "RTD", "RNC")]
num_vars <- c("MAT", "MAP", "Exudation", "AvaiP", "TP", "RD", "SRL", "RTD", "RNC")
semdata <- as.data.frame(semdata)
semdata[, num_vars] <- scale(semdata[, num_vars])
semdata$Mycorrhizal_types_num <- as.numeric(semdata$Mycorrhizal_types_num)

dat_blocks <- list(
  climate   = c("MAT", "MAP"),
  MT        = c("Mycorrhizal_types_num"),
  root      = c("RD", "SRL", "RTD", "RNC"),
  AP        = c("TP", "AvaiP"),
  Exudation = c("Exudation")
)

climate   <- c(0, 0, 0, 0, 0)
MT        <- c(0, 0, 0, 0, 0)
root      <- c(1, 1, 0, 0, 0)
AP        <- c(1, 1, 0, 0, 0)
Exudation <- c(1, 1, 1, 1, 0)

dat_path <- rbind(climate, MT, root, AP, Exudation)
colnames(dat_path) <- rownames(dat_path) <- names(dat_blocks)
pls_mod <- rep("A", length(colnames(dat_path)))
dat_pls <- plspm(semdata, dat_path, dat_blocks, modes = pls_mod, boot.val = TRUE, br = 1000)
summary(dat_pls)

dat_pls$path_coefs
dat_pls$inner_model
innerplot(dat_pls, lcol = "grey50")
dat_pls$inner_summary
dat_pls$effects
dat_pls$outer_model
outerplot(
  dat_pls,
  what = "loadings",
  lcol = "grey50",
  arr.width = 0.05,
  box.size = 0.1
)

dat_pls$gof

boot_loadings <- dat_pls$boot$loadings
boot_loadings$p_value <- 2 * pnorm(
  -abs(boot_loadings$Mean / boot_loadings$Std.Error)
)
boot_loadings$significant_95CI <- boot_loadings$perc.025 * boot_loadings$perc.975 > 0
print(boot_loadings)

